#
# Script used by the BuildPackageTest.cmake module.
#

message(STATUS "Running script '${CMAKE_CURRENT_LIST_FILE}'")
message(STATUS "  executing command '\"${CMAKE_COMMAND}\" --build . --config \"${config}\" --target package'")
message(STATUS "  in binary_dir='@binary_dir@'")
message(STATUS "")

set(results_script "@binary_dir@/BuildPackageTestResults.cmake")
file(REMOVE "${results_script}")

execute_process(
  COMMAND ${CMAKE_COMMAND} --build . --config "${config}" --target package
  WORKING_DIRECTORY "@binary_dir@"
  OUTPUT_VARIABLE output
  RESULT_VARIABLE result
  )

message(STATUS "output:")
message(STATUS "${output}")
message(STATUS "")

if(NOT "${result}" STREQUAL "0")
  message(FATAL_ERROR "error: --build package call returned '${result}'")
endif()


#
# Construct a list of package files by scraping individual file names from
# the 'make package' output:
#
set(packages)
set(regex "package: ([^\n]+) generated")

string(REGEX MATCHALL "${regex}" package_lines "${output}")
foreach(line ${package_lines})
  string(REGEX REPLACE "${regex}" "\\1" package "${line}")
  list(APPEND packages "${package}")
endforeach()


#
# Write out a helper script that can be used later to upload these:
#
file(WRITE "${results_script}" "# BuildPackageTestResults.cmake
#   generated by \"${CMAKE_CURRENT_LIST_FILE}\"
#
set(package_files \"${packages}\")
")
